//
//  VideoCommentController.swift
//  Gamers
//
//  Created by 虚空之翼 on 15/8/21.
//  Copyright (c) 2015年 Freedom. All rights reserved.
//

import UIKit
import Bolts
import MJRefresh
import DBAlertController
//import SCLAlertView

class VideoCommentController: UIViewController {
    let userDefaults = NSUserDefaults.standardUserDefaults()    //用户全局登入信息
    
    var videoData: Video!
    var commentData = [YTVComment]()
    var pageToken = ""          //分页偏移量，默认为上次最后一个视频ID的nextpagetoken
    var maxResults = 20         //每页评论数量
    
    var isNoMoreData: Bool = false  //解决控件不能自己判断BUG
    // 键盘属性,输入框
    var keyboardMoveStatus: Bool = false
    var keyboardHeight: CGFloat = 0
    var chatToolViewMoveStatus: Bool = false
    
    @IBOutlet weak var commentTableView: UITableView!
    @IBOutlet weak var chatToolView: UIView!
    @IBOutlet weak var chatCommentText: UITextField!
    @IBAction func chatSendButton(sender: AnyObject) {
        moveDown(keyboardHeight)

        // 插入数据
//        if chatCommentText.text != "" {
//            if isGoogleLogin() {
//                print("已登入")
//                insertComment(chatCommentText.text!)
//            }
//        } else {
//            print("评论内容空")
//        }
        insertComment(chatCommentText.text!)
        chatCommentText.text = "" //清空输入
    }
    
    var dismissAlertClosure: (() -> Void)?
    var dataLoadingDone = false {
        didSet {
            if dataLoadingDone == true {
                dismissAlertClosure?()
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 刷新功能
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData")
        header.setTitle(NSLocalizedString("MJRefreshHeaderIdleText", comment: "Pull down to refresh"), forState: MJRefresh.MJRefreshStateIdle)
        header.setTitle(NSLocalizedString("MJRefreshHeaderPullingText", comment: "Release to refresh"), forState: MJRefresh.MJRefreshStatePulling)
        header.setTitle(NSLocalizedString("MJRefreshHeaderRefreshingText", comment: "Loading ..."), forState: MJRefresh.MJRefreshStateRefreshing)
        commentTableView.header = header
        let footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMoreData")
        footer.setTitle(NSLocalizedString("MJRefreshAutoFooterIdleText", comment: "Click or drag up to refresh"), forState: MJRefresh.MJRefreshStateIdle)
        footer.setTitle(NSLocalizedString("MJRefreshAutoFooterRefreshingText", comment: "Loading more ..."), forState: MJRefresh.MJRefreshStateRefreshing)
        footer.setTitle(NSLocalizedString("MJRefreshAutoFooterNoMoreDataText", comment: "No more data"), forState: MJRefresh.MJRefreshStateNoMoreData)
        commentTableView.footer = footer

        // 删除多余的分割线
        self.commentTableView.tableFooterView = UIView(frame: CGRectZero)
        // cell分割线边距，ios8处理
        if self.commentTableView.respondsToSelector("setSeparatorInset:") {
            self.commentTableView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
        }
        if self.commentTableView.respondsToSelector("setLayoutMargins:") {
            self.commentTableView.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
        }
        
        // 设置手势点击数,收起键盘
        //let tapGesture = UITapGestureRecognizer(target: self, action: "handleTapGesture:")
        //tapGesture.numberOfTapsRequired = 1
        //self.view.addGestureRecognizer(tapGesture)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadVideoComment:", name: "reloadVideoCommentNotification", object: nil)
        // 重新加载视频评论监听器，键盘收起监听器
        //NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHide:", name: UIKeyboardWillHideNotification, object: nil)
        //NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardShow:", name: UIKeyboardWillShowNotification, object: nil)
        //NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTapGesture:", name: "handleTapGestureNotification", object: nil)
        
        //commentTableView.estimatedRowHeight = 10.0;
        //commentTableView.rowHeight = UITableViewAutomaticDimension;
        
        //chatCommentText.delegate = self
        
        // 加载初始化数据
        loadInit()
        
        
        

    }

    // 初始化数据
    func loadInit() {
        pageToken = ""
        
        VideoBL.sharedSingleton.getYoutubeComment(videoData.videoId, pageToken: pageToken, maxResults: maxResults).continueWithExecutor(BFExecutor.mainThreadExecutor(), withSuccessBlock: { [weak self] (task: BFTask!) -> BFTask! in
            if let newData = task.result as? [YTVComment] {
                self!.commentData = newData
                if !self!.commentData.isEmpty {
                    self?.commentTableView.reloadData()
                    if self!.commentData.last!.nextPageToken == "" {
                        self?.commentTableView.footer.endRefreshingWithNoMoreData()
                        self!.isNoMoreData = true
                    } else {
                        self!.pageToken = self!.commentData.last!.nextPageToken
                    }
                }

            } else {
                self?.commentTableView.footer.endRefreshingWithNoMoreData()
                print("错误：\(task.result)")
            }

            return nil
        }).continueWithBlock({(task: BFTask!) -> BFTask! in
            NSNotificationCenter.defaultCenter().postNotificationName("MBProgressHUDHideNotification", object: nil, userInfo: nil)
            return nil
        })
        
    }
    
    
    // 下拉重新刷新数据
    func loadNewData() {
        pageToken = ""
        isNoMoreData = false
        VideoBL.sharedSingleton.getYoutubeComment(videoData.videoId, pageToken: pageToken, maxResults: maxResults).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
            if let newData = task.result as? [YTVComment] {
                self!.commentData = newData
                if !self!.commentData.isEmpty {
                    self?.commentTableView.reloadData()
                    if self!.commentData.last!.nextPageToken == "" {
                        self?.commentTableView.footer.endRefreshingWithNoMoreData()
                        self!.isNoMoreData = true
                    } else {
                        self!.pageToken = self!.commentData.last!.nextPageToken
                    }
                }
                
            } else {
                self?.commentTableView.footer.endRefreshingWithNoMoreData()
                print("错误：\(task.result)")
            }
            return nil
        }).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
            self?.commentTableView.header.endRefreshing()
            // 刷新Google的token
            if (self!.userDefaults.stringForKey("googleRefreshToken") != nil) {
                UserBL.sharedSingleton.googleRefreshToken()
            }
            
            return nil
        })
    }
    // 上拉加载更多数据
    func loadMoreData() {
        VideoBL.sharedSingleton.getYoutubeComment(videoData.videoId, pageToken: pageToken, maxResults: maxResults).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
            if let newData = (task.result as? [YTVComment]) {
                if newData.isEmpty {
                    self?.commentTableView.footer.endRefreshingWithNoMoreData()
                    self!.isNoMoreData = true
                } else{
                    self!.commentData += newData
                    
                    if newData.last!.nextPageToken == "" {
                        self?.commentTableView.footer.endRefreshingWithNoMoreData()
                        self!.isNoMoreData = true
                    } else {
                        self!.pageToken = self!.commentData.last!.nextPageToken
                    }
                    
                    self?.commentTableView.reloadData()
                }
            }

            return nil
        }).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
            if !self!.isNoMoreData {
                self?.commentTableView.footer.endRefreshing()
            }
            
            // 刷新Google的token
            if (self!.userDefaults.stringForKey("googleRefreshToken") != nil) {
                UserBL.sharedSingleton.googleRefreshToken()
            }

            return nil
        })
    }
    
    // 重新加载视频评论
    func reloadVideoComment(notification: NSNotification) {
        let userInfo = notification.userInfo!
        self.videoData = userInfo["data"] as! Video

        loadInit()
    }
    
    // 提交评论
    func insertComment(commentText: String) {


        if commentText == "" {
            print("内容为空")
        } else {
            VideoBL.sharedSingleton.InsertVideoComment(videoData.videoId, textOriginal: commentText).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
                if let responseData = task.result as? YTVComment {
                    let newComment = YTVComment()
                    newComment.textDisplay = responseData.textOriginal
                    newComment.authorDisplayName = responseData.authorDisplayName
                    newComment.publishedAt = responseData.publishedAt
                    
                    self!.commentData.insert(newComment, atIndex: 0)
                    // 清空数据
                    //self?.commentText.text = ""
                    // 在表格头部新增数据
                    self?.commentTableView.beginUpdates()
                    //var indexPathsToInsert = NSMutableArray()
                    //indexPathsToInsert.addObject(NSIndexPath(forRow: 0, inSection: 0))
                    self?.commentTableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Top)
                    self?.commentTableView.endUpdates()
                    
                } else {
//                    let actionSheetController: UIAlertController = UIAlertController(title: "", message: NSLocalizedString("You need to be logged YouTube, whether or login?", comment: "需要登入YouTube，是否登入？"), preferredStyle: UIAlertControllerStyle.Alert)
//                    actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("No", comment: "否"), style: UIAlertActionStyle.Cancel, handler: { (alertAction) -> Void in
//                        //
//                    }))
//                    actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "是"), style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
//                        let userInfoView = self!.storyboard!.instantiateViewControllerWithIdentifier("GoogleLoginVC") as? GoogleLoginController
//                        
//                        self!.navigationController?.pushViewController(userInfoView!, animated: true)
//                    }))
//                
//                    // 显示Sheet
//                    BasicFunction.delay(1, completion: { () -> () in
//                        self!.presentViewController(actionSheetController, animated: true, completion: nil)
//                    })
                    print("调用警告！")
                    self!.view.endEditing(true)
                    let actionSheetController2 = UIAlertController(title: "", message: NSLocalizedString("You need to be logged Freedom, whether or login?", comment: "需要登入Freedom，是否登入？"), preferredStyle: UIAlertControllerStyle.Alert)
                    actionSheetController2.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "是"), style: UIAlertActionStyle.Cancel, handler: nil))
                    //self!.presentViewController(actionSheetController2, animated: true, completion: nil)
                    

//                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//                        
//                        [NSThread sleepForTimeInterval:0.1];
//                        
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            // アラートを閉じる
//                            [alert dismissViewControllerAnimated:YES completion:^{
//                                // 次のモーダルビューを表示
//                                [self presentViewController:[ModalViewController new] animated:YES completion:nil];
//                                }];
//                            });
//                        });
//                    BasicFunction.delay(1, completion: { () -> () in
//                        actionSheetController2.dismissViewControllerAnimated(true, completion: { () -> Void in
//                            self?.presentViewController(actionSheetController2, animated: true, completion: nil)
//                        })
//                    })
                    //SCLAlertView().showInfo("Important info", subTitle: "You are great")
                    
                }
                
                return nil
            }).continueWithBlock({ (task: BFTask!) -> BFTask! in
                if task.error != nil { print(task.error) }
                return nil
            })
        }
    }

    
    // 屏幕和键盘上移
    func moveUp(upHeight: CGFloat) {
        if !keyboardMoveStatus {
            keyboardMoveStatus = true

            //设置动画的名字
            UIView.beginAnimations("Animation", context: nil)
            //设置动画的间隔时间
            UIView.setAnimationDuration(0.20)
            //使用当前正在运行的状态开始下一段动画
            UIView.setAnimationBeginsFromCurrentState(true)
            //设置视图移动的位移
            self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - upHeight, self.view.frame.size.width, self.view.frame.size.height);

            //设置动画结束
            UIView.commitAnimations()
            //隐藏后退键防止早退错误
            self.navigationItem.hidesBackButton = true

        }
    }
    // 屏幕和键盘下移
    func moveDown(upHeight: CGFloat) {
        if keyboardMoveStatus {
            print("键盘下移")
            keyboardMoveStatus = false

            //设置动画的名字
            UIView.beginAnimations("Animation2", context: nil)
            //设置动画的间隔时间
            UIView.setAnimationDuration(0.20)
            //??使用当前正在运行的状态开始下一段动画
            UIView.setAnimationBeginsFromCurrentState(true)
            //设置视图移动的位移
            self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + upHeight, self.view.frame.size.width, self.view.frame.size.height);
            //self.chatToolView.frame = CGRectMake(self.chatToolView.frame.origin.x, self.chatToolView.frame.origin.y + upHeight, self.chatToolView.frame.size.width, self.chatToolView.frame.size.height);
            //设置动画结束
            UIView.commitAnimations()

            //显示后退键
            self.navigationItem.hidesBackButton = false
            
            // 收起键盘
            keyboardHeight = 0
        }
    }
    
    // 隐藏键盘
    func handleTapGesture(sender: UITapGestureRecognizer) {
        print("键盘隐藏1")
        self.moveDown(self.keyboardHeight)
        //println("触发了点击事件")
        
        
        if self.chatCommentText.isFirstResponder() {
            self.chatCommentText.resignFirstResponder()
        }

    }
    
    // 第一步监听键盘弹出，获取键盘的高度
    func keyboardShow(notification: NSNotification) {
        let userInfo = notification.userInfo!
        let keyObject = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
        keyboardHeight = keyObject.CGRectValue().size.height
        
        moveUp(keyObject.CGRectValue().size.height)
    }
    func keyboardHide(notification: NSNotification) {
        print("键盘隐藏2")
        moveDown(keyboardHeight)
    }
    //输入法更换时，处理键盘高度发送变化情况
    func keyboardChange(notification: NSNotification) {
        if keyboardMoveStatus {
            let userInfo = notification.userInfo!
            let keyObject = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
            let newKeyboardHeight = keyObject.CGRectValue().size.height
            //println("高度差：\(newKeyboardHeight - keyboardHeight)")
            //设置动画的名字
            UIView.beginAnimations("Animation3", context: nil)
            //设置动画的间隔时间
            UIView.setAnimationDuration(0.20)
            //??使用当前正在运行的状态开始下一段动画
            UIView.setAnimationBeginsFromCurrentState(true)
            //设置视图移动的位移
            self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - newKeyboardHeight + keyboardHeight, self.view.frame.size.width, self.view.frame.size.height);
            //设置动画结束
            UIView.commitAnimations()
            
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    

}

// MARK: - 表格代理协议
extension VideoCommentController: UITableViewDataSource, UITableViewDelegate {
    // 设置表格行数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if commentData.isEmpty {
            return 1
        } else {
            return commentData.count
        }
    }
    // 设置单元格
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if commentData.isEmpty {
            let cell = tableView.dequeueReusableCellWithIdentifier("VideoCommentNoDataCell", forIndexPath: indexPath)
            return cell
        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("VideoCommentCell", forIndexPath: indexPath) as! VideoCommentCell
            cell.setComment(self.commentData[indexPath.row])
            
            return cell
        }
    }
    // cell分割线的边距
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if cell.respondsToSelector("setSeparatorInset:") {
            cell.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
        }
        if cell.respondsToSelector("setLayoutMargins:") {
            cell.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
        }
    }
    // cell自动行高设置
//    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        if commentData.isEmpty {
//            return view.frame.size.height
//        } else {
//            return tableView.fd_heightForCellWithIdentifier("VideoCommentCell", cacheByIndexPath: indexPath) { (cell) -> Void in
//                cell.setComment(self.commentData[indexPath.row])
//            }
//        }
//    }
    // 发出收起键盘事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        NSNotificationCenter.defaultCenter().postNotificationName("handleTapGestureNotification", object: nil, userInfo: nil)
    }
    
}
// MARK: - 文本框代理协议，键盘的收起和输入上下移动
extension VideoCommentController: UITextFieldDelegate, UITextViewDelegate {
    // 键盘和文本框输入事件
    func textFieldDidBeginEditing(textField: UITextField) {
        //moveUp(keyboardHeight)
        //isGoogleLogin()
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        // 插入数据
//        if chatCommentText.text != "" {
//            if isGoogleLogin() {
//                insertComment(chatCommentText.text!)
//            }
//        } else {
//            print("评论内容空")
//        }
        //insertComment(chatCommentText.text!)
        //chatCommentText.text = "" //清空输入
        
//SCLAlertView().showInfo("Important info", subTitle: "You are great")
        // 收起键盘
        //self.view.endEditing(true)
        //self.chatCommentText.endEditing(true)
        print("Return")
        self.view.endEditing(true)
        self.chatCommentText.resignFirstResponder()


        //keyboardHeight = 0

        
        return true
    }

    
    // 判断是否登入Google
    func isGoogleLogin() -> Bool {
        let googleAccessToken = userDefaults.stringForKey("userToken")
        let googleBeginTime = userDefaults.integerForKey("beginTime")
        let now = Int(NSDate().dateByAddingTimeInterval(0).timeIntervalSince1970)
        
        // googleAccessToken == nil || (googleBeginTime != nil && now - googleBeginTime! > 3600)
        if googleAccessToken == nil || now - googleBeginTime > 3600 {
            self.view.endEditing(true)
            let actionSheetController1 = UIAlertController(title: "", message: NSLocalizedString("You need to be logged Freedom, whether or login?", comment: "需要登入Freedom，是否登入？"), preferredStyle: UIAlertControllerStyle.Alert)
            actionSheetController1.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "是"), style: UIAlertActionStyle.Cancel, handler: { (UIAlertAction) -> Void in
                self.view.endEditing(true)
            }))
            //actionSheetController.show()
            
            BasicFunction.delay(1, completion: { () -> () in
                self.presentViewController(actionSheetController1, animated: true, completion: nil)
            })

//            // Set the dismiss closure to perform later with a reference to alert
//            dismissAlertClosure = {
//                actionSheetController.dismissViewControllerAnimated(true, completion: nil)
//            }
//            
//            // Set boolValue to true in 5 seconds in order to simulate your asynchronous request completion
//            let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))
//            dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.dataLoadingDone = true })
            
//            if (![[self controller] isBeingDismissed]) {
//                [self dismissViewControllerAnimated:YES completion:NULL];
//            }
            
//            UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
//            [rootViewController presentViewController: alert animated: YES completion: nil];
            
            
            return false
        } else {
            return true
        }
        
    }
    
    
    
}
